import { ref, computed } from 'vue'
import { invoke } from '@tauri-apps/api/core'
import router from '../router'

interface User {
  id: string
  username: string
  email?: string
  token: string
}

interface LoginResponse {
  data?: User
  msg?: string
  status: boolean
  code: number
}

// Global reactive state
const isLoggedIn = ref(false)
const currentUser = ref<User | null>(null)
const isCheckingAuth = ref(false)

export const useAuth = () => {
  // Check login status from Tauri backend
  const checkLoginStatus = async (): Promise<boolean> => {
    try {
      isCheckingAuth.value = true
      const hasSession = await invoke<boolean>('is_user_logged_in')
      
      if (hasSession) {
        // Get current user from session
        const user = await invoke<User | null>('get_session_user')
        if (user) {
          currentUser.value = user
          isLoggedIn.value = true
          
          // Sync with localStorage for consistency
          localStorage.setItem('isLoggedIn', 'true')
          localStorage.setItem('currentUser', JSON.stringify(user))
          
          return true
        }
      }
      
      // No valid session found
      isLoggedIn.value = false
      currentUser.value = null
      localStorage.removeItem('isLoggedIn')
      localStorage.removeItem('currentUser')
      
      return false
    } catch (error) {
      console.error('Failed to check login status:', error)
      isLoggedIn.value = false
      currentUser.value = null
      return false
    } finally {
      isCheckingAuth.value = false
    }
  }

  // Initialize auth state from localStorage (for faster UI updates)
  const initializeAuthFromStorage = () => {
    const savedLogin = localStorage.getItem('isLoggedIn')
    const savedUser = localStorage.getItem('currentUser')
    
    if (savedLogin === 'true' && savedUser) {
      try {
        currentUser.value = JSON.parse(savedUser)
        isLoggedIn.value = true
      } catch (e) {
        console.error('Failed to parse saved user data:', e)
        localStorage.removeItem('isLoggedIn')
        localStorage.removeItem('currentUser')
      }
    }
  }

  // Login function
  const login = async (credentials: { username: string; password: string }): Promise<LoginResponse> => {
    try {
      const result = await invoke<LoginResponse>('login', { credentials })
      
      if (result.status && result.data) {
        currentUser.value = result.data
        isLoggedIn.value = true
        
        // Save to localStorage
        localStorage.setItem('isLoggedIn', 'true')
        localStorage.setItem('currentUser', JSON.stringify(result.data))
      }
      
      return result
    } catch (error: any) {
      console.error('Login error:', error)
      return {
        status: false,
        code: 500,
        msg: error.message || '登录失败，请稍后重试'
      }
    }
  }

  // Logout function
  const logout = async () => {
    try {
      if (currentUser.value?.token) {
        await invoke('logout', { token: currentUser.value.token })
      }
    } catch (error) {
      console.error('Logout error:', error)
    } finally {
      // Clear state regardless of backend result
      isLoggedIn.value = false
      currentUser.value = null
      localStorage.removeItem('isLoggedIn')
      localStorage.removeItem('currentUser')
      
      // Redirect to login
      await router.push('/')
      
      // Emit logout event for other components
      window.dispatchEvent(new CustomEvent('user-logout'))
    }
  }

  // Require authentication - redirect to login if not authenticated
  const requireAuth = async (): Promise<boolean> => {
    if (!isLoggedIn.value) {
      const hasValidSession = await checkLoginStatus()
      if (!hasValidSession) {
        await router.push('/')
        return false
      }
    }
    return true
  }

  // Computed properties
  const userDisplayName = computed(() => {
    return currentUser.value?.username || currentUser.value?.email || '用户'
  })

  const hasValidToken = computed(() => {
    return !!currentUser.value?.token
  })

  return {
    // State
    isLoggedIn: computed(() => isLoggedIn.value),
    currentUser: computed(() => currentUser.value),
    isCheckingAuth: computed(() => isCheckingAuth.value),
    userDisplayName,
    hasValidToken,

    // Methods
    checkLoginStatus,
    initializeAuthFromStorage,
    login,
    logout,
    requireAuth
  }
}